import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/check_in_record.dart';
import '../models/check_in_goal.dart';
import '../repositories/check_in_record_repository.dart';
import '../repositories/check_in_goal_repository.dart';
import '../services/check_in_export_service.dart';
import 'dart:io';
import 'package:fl_chart/fl_chart.dart';

class CheckInScreen extends StatefulWidget {
  const CheckInScreen({super.key});

  @override
  State<CheckInScreen> createState() => _CheckInScreenState();
}

class _CheckInScreenState extends State<CheckInScreen> with SingleTickerProviderStateMixin {
  final CheckInRecordRepository _recordRepository = CheckInRecordRepository();
  final CheckInGoalRepository _goalRepository = CheckInGoalRepository();
  final CheckInExportService _exportService = CheckInExportService();
  
  bool _isLoading = true;
  bool _isCheckedInToday = false;
  List<CheckInRecord> _checkIns = [];
  List<CheckInGoal> _goals = [];
  Map<String, dynamic> _stats = {};
  
  // 当前选中的标签页
  late TabController _tabController;
  
  // 新目标表单控制器
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _targetValueController = TextEditingController();
  final _unitController = TextEditingController();
  
  // 签到表单控制器
  final _studyTimeController = TextEditingController(text: '0');
  final _wordsLearnedController = TextEditingController(text: '0');
  final _questionsAnsweredController = TextEditingController(text: '0');
  final _noteController = TextEditingController();
  
  // 目标进度控制器映射
  final Map<int, TextEditingController> _goalProgressControllers = {};
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadData();
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    _titleController.dispose();
    _descriptionController.dispose();
    _targetValueController.dispose();
    _unitController.dispose();
    _studyTimeController.dispose();
    _wordsLearnedController.dispose();
    _questionsAnsweredController.dispose();
    _noteController.dispose();
    _goalProgressControllers.forEach((_, controller) => controller.dispose());
    super.dispose();
  }
  
  // 加载数据
  Future<void> _loadData() async {
    setState(() => _isLoading = true);
    
    try {
      // 从数据库加载签到记录
      final records = await _recordRepository.getAllCheckInRecords();
      records.sort((a, b) => b.date.compareTo(a.date)); // 按日期降序排序
      
      // 从数据库加载签到目标
      final goals = await _goalRepository.getAllCheckInGoals();
      
      // 检查今日是否已签到
      final isCheckedIn = await _recordRepository.isTodayCheckedIn();
      
      // 获取签到统计数据
      final stats = await _recordRepository.getCheckInStats();
      
      // 为每个目标创建进度控制器
      for (final goal in goals) {
        if (goal.id != null && !_goalProgressControllers.containsKey(goal.id)) {
          _goalProgressControllers[goal.id!] = TextEditingController(text: '0');
        }
      }
      
      setState(() {
        _checkIns = records;
        _goals = goals;
        _isCheckedInToday = isCheckedIn;
        _stats = stats;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      _showErrorSnackBar('加载签到数据失败: $e');
    }
  }
  
  // 显示签到表单
  void _showCheckInForm() {
    // 重置表单控制器
    _studyTimeController.text = '0';
    _wordsLearnedController.text = '0';
    _questionsAnsweredController.text = '0';
    _noteController.text = '';
    
    // 重置目标进度控制器
    for (final entry in _goalProgressControllers.entries) {
      entry.value.text = '0';
    }
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('今日签到'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextField(
                controller: _studyTimeController,
                decoration: const InputDecoration(labelText: '学习时长（分钟）'),
                keyboardType: TextInputType.number,
              ),
              TextField(
                controller: _wordsLearnedController,
                decoration: const InputDecoration(labelText: '学习单词数'),
                keyboardType: TextInputType.number,
              ),
              TextField(
                controller: _questionsAnsweredController,
                decoration: const InputDecoration(labelText: '答题数量'),
                keyboardType: TextInputType.number,
              ),
              TextField(
                controller: _noteController,
                decoration: const InputDecoration(labelText: '备注'),
                maxLines: 2,
              ),
              if (_goals.isNotEmpty) const SizedBox(height: 16),
              if (_goals.isNotEmpty)
                const Text('目标进度', style: TextStyle(fontWeight: FontWeight.bold)),
              ..._goals.where((goal) => goal.isActive).map((goal) {
                final controller = _goalProgressControllers[goal.id] ?? TextEditingController(text: '0');
                return Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: TextField(
                    controller: controller,
                    decoration: InputDecoration(
                      labelText: '${goal.title} (${goal.unit})',
                      helperText: '目标: ${goal.targetValue} ${goal.unit}',
                    ),
                    keyboardType: TextInputType.number,
                  ),
                );
              }).toList(),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _checkIn();
            },
            child: const Text('签到'),
          ),
        ],
      ),
    );
  }
  
  // 执行签到
  Future<void> _checkIn() async {
    try {
      // 获取表单数据
      final studyTime = int.tryParse(_studyTimeController.text) ?? 0;
      final wordsLearned = int.tryParse(_wordsLearnedController.text) ?? 0;
      final questionsAnswered = int.tryParse(_questionsAnsweredController.text) ?? 0;
      final note = _noteController.text;
      
      // 获取目标进度数据
      final Map<int, int> goalProgress = {};
      for (final entry in _goalProgressControllers.entries) {
        final goalId = entry.key;
        final progress = int.tryParse(entry.value.text) ?? 0;
        goalProgress[goalId] = progress;
      }
      
      // 创建签到记录
      final now = DateTime.now();
      final today = DateTime(now.year, now.month, now.day);
      final record = CheckInRecord(
        date: today.millisecondsSinceEpoch,
        studyTime: studyTime,
        wordsLearned: wordsLearned,
        questionsAnswered: questionsAnswered,
        note: note,
        createdAt: now.millisecondsSinceEpoch,
        goalProgress: goalProgress,
      );
      
      // 保存到数据库
      await _recordRepository.addCheckInRecord(record);
      
      // 重新加载数据
      await _loadData();
      
      _showSuccessSnackBar('签到成功！');
    } catch (e) {
      _showErrorSnackBar('签到失败，请重试: $e');
    }
  }
  
  // 取消今日签到
  Future<void> _cancelTodayCheckIn() async {
    try {
      // 获取今日签到记录
      final todayRecord = await _recordRepository.getTodayCheckInRecord();
      if (todayRecord != null && todayRecord.id != null) {
        // 从数据库删除
        await _recordRepository.deleteCheckInRecord(todayRecord.id!);
        
        // 重新加载数据
        await _loadData();
        
        _showSuccessSnackBar('已取消今日签到');
      }
    } catch (e) {
      _showErrorSnackBar('取消签到失败，请重试: $e');
    }
  }
  
  // 显示确认取消签到对话框
  void _showCancelConfirmDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('取消签到'),
        content: const Text('确定要取消今日签到吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _cancelTodayCheckIn();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
  
  // 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }
  
  // 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  // 显示添加目标表单
  void _showAddGoalForm() {
    // 重置表单控制器
    _titleController.text = '';
    _descriptionController.text = '';
    _targetValueController.text = '';
    _unitController.text = '';
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加签到目标'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _titleController,
                decoration: const InputDecoration(labelText: '目标标题 *'),
              ),
              TextField(
                controller: _descriptionController,
                decoration: const InputDecoration(labelText: '目标描述'),
                maxLines: 2,
              ),
              TextField(
                controller: _targetValueController,
                decoration: const InputDecoration(labelText: '目标值 *'),
                keyboardType: TextInputType.number,
              ),
              TextField(
                controller: _unitController,
                decoration: const InputDecoration(labelText: '单位 *（如：分钟、个）'),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 验证表单
              if (_titleController.text.isEmpty ||
                  _targetValueController.text.isEmpty ||
                  _unitController.text.isEmpty) {
                _showErrorSnackBar('请填写必填字段');
                return;
              }
              
              Navigator.pop(context);
              _addGoal();
            },
            child: const Text('保存'),
          ),
        ],
      ),
    );
  }
  
  // 添加签到目标
  Future<void> _addGoal() async {
    try {
      // 获取表单数据
      final title = _titleController.text;
      final description = _descriptionController.text;
      final targetValue = int.tryParse(_targetValueController.text) ?? 0;
      final unit = _unitController.text;
      
      print('添加目标: $title, $description, $targetValue, $unit');
      
      // 创建目标
      final now = DateTime.now().millisecondsSinceEpoch;
      final goal = CheckInGoal(
        title: title,
        description: description,
        targetValue: targetValue,
        unit: unit,
        isActive: true,
        createdAt: now,
        updatedAt: now,
      );
      
      print('创建的目标对象: $goal');
      
      // 保存到数据库
      final result = await _goalRepository.addCheckInGoal(goal);
      print('添加目标结果: $result');
      
      // 重新加载数据
      await _loadData();
      
      _showSuccessSnackBar('目标添加成功！');
    } catch (e, stackTrace) {
      print('添加目标失败: $e');
      print('错误堆栈: $stackTrace');
      _showErrorSnackBar('添加目标失败: $e');
    }
  }
  
  // 删除签到目标
  Future<void> _deleteGoal(int id) async {
    try {
      await _goalRepository.deleteCheckInGoal(id);
      await _loadData();
      _showSuccessSnackBar('目标已删除');
    } catch (e) {
      _showErrorSnackBar('删除目标失败: $e');
    }
  }
  
  // 切换目标激活状态
  Future<void> _toggleGoalActive(int id, bool isActive) async {
    try {
      await _goalRepository.toggleGoalActive(id, isActive);
      await _loadData();
      _showSuccessSnackBar(isActive ? '目标已激活' : '目标已停用');
    } catch (e) {
      _showErrorSnackBar('操作失败: $e');
    }
  }
  
  // 导出签到记录为CSV
  Future<void> _exportToCsv() async {
    try {
      final result = await _exportService.exportToCsv();
      if (result.startsWith('导出失败')) {
        _showErrorSnackBar(result);
      } else {
        _showSuccessSnackBar('导出成功: $result');
      }
    } catch (e) {
      _showErrorSnackBar('导出失败: $e');
    }
  }
  
  // 导出签到记录为Excel
  Future<void> _exportToExcel() async {
    try {
      final result = await _exportService.exportToExcel();
      if (result.startsWith('导出失败')) {
        _showErrorSnackBar(result);
      } else {
        _showSuccessSnackBar('导出成功: $result');
      }
    } catch (e) {
      _showErrorSnackBar('导出失败: $e');
    }
  }
  
  // 显示导出选项菜单
  void _showExportMenu() {
    showModalBottomSheet(
      context: context,
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.file_present),
              title: const Text('导出为CSV'),
              onTap: () {
                Navigator.pop(context);
                _exportToCsv();
              },
            ),
            ListTile(
              leading: const Icon(Icons.table_chart),
              title: const Text('导出为Excel'),
              onTap: () {
                Navigator.pop(context);
                _exportToExcel();
              },
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建签到统计卡片
  Widget _buildStatsCard() {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('签到统计', style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('总签到天数', _stats['totalDays']?.toString() ?? '0'),
                _buildStatItem('连续签到', _stats['consecutiveDays']?.toString() ?? '0'),
                _buildStatItem('本月签到', _stats['thisMonthDays']?.toString() ?? '0'),
              ],
            ),
            const SizedBox(height: 16),
            Text('学习数据', style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('总学习时长', '${_stats['totalStudyTime']?.toString() ?? '0'}分钟'),
                _buildStatItem('总单词量', _stats['totalWordsLearned']?.toString() ?? '0'),
                _buildStatItem('总答题量', _stats['totalQuestionsAnswered']?.toString() ?? '0'),
              ],
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建统计项
  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
        Text(label, style: const TextStyle(color: Colors.grey)),
      ],
    );
  }
  
  // 构建签到记录图表
  Widget _buildCheckInChart() {
    // 获取最近30天的数据
    final recentRecords = _checkIns.take(30).toList();
    if (recentRecords.isEmpty) {
      return const Center(child: Text('暂无数据'));
    }
    
    // 准备图表数据
    final studyTimeSpots = <FlSpot>[];
    final wordsLearnedSpots = <FlSpot>[];
    final questionsAnsweredSpots = <FlSpot>[];
    
    for (var i = 0; i < recentRecords.length; i++) {
      final record = recentRecords[i];
      studyTimeSpots.add(FlSpot(i.toDouble(), record.studyTime.toDouble()));
      wordsLearnedSpots.add(FlSpot(i.toDouble(), record.wordsLearned.toDouble()));
      questionsAnsweredSpots.add(FlSpot(i.toDouble(), record.questionsAnswered.toDouble()));
    }
    
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('学习趋势', style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 16),
          SizedBox(
            height: 200,
            child: LineChart(
              LineChartData(
                gridData: FlGridData(show: false),
                titlesData: FlTitlesData(show: false),
                borderData: FlBorderData(show: true),
                lineBarsData: [
                  LineChartBarData(
                    spots: studyTimeSpots,
                    isCurved: true,
                    color: Colors.blue,
                    barWidth: 3,
                    isStrokeCapRound: true,
                    dotData: FlDotData(show: false),
                    belowBarData: BarAreaData(show: false),
                  ),
                  LineChartBarData(
                    spots: wordsLearnedSpots,
                    isCurved: true,
                    color: Colors.green,
                    barWidth: 3,
                    isStrokeCapRound: true,
                    dotData: FlDotData(show: false),
                    belowBarData: BarAreaData(show: false),
                  ),
                  LineChartBarData(
                    spots: questionsAnsweredSpots,
                    isCurved: true,
                    color: Colors.orange,
                    barWidth: 3,
                    isStrokeCapRound: true,
                    dotData: FlDotData(show: false),
                    belowBarData: BarAreaData(show: false),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildChartLegend('学习时长', Colors.blue),
              const SizedBox(width: 16),
              _buildChartLegend('单词量', Colors.green),
              const SizedBox(width: 16),
              _buildChartLegend('答题量', Colors.orange),
            ],
          ),
        ],
      ),
    );
  }
  
  // 构建图表图例
  Widget _buildChartLegend(String label, Color color) {
    return Row(
      children: [
        Container(
          width: 12,
          height: 12,
          color: color,
        ),
        const SizedBox(width: 4),
        Text(label),
      ],
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('每日签到'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.file_download),
            onPressed: _checkIns.isEmpty ? null : _showExportMenu,
            tooltip: '导出签到记录',
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '签到'),
            Tab(text: '数据'),
            Tab(text: '目标'),
          ],
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : TabBarView(
              controller: _tabController,
              children: [
                // 签到页面
                SingleChildScrollView(
                  child: Column(
                    children: [
                      // 签到卡片
                      Card(
                        margin: const EdgeInsets.all(16),
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            children: [
                              Text(
                                _isCheckedInToday ? '今日已签到' : '今日未签到',
                                style: Theme.of(context).textTheme.headlineSmall,
                              ),
                              const SizedBox(height: 16),
                              _isCheckedInToday
                                  ? ElevatedButton.icon(
                                      onPressed: _showCancelConfirmDialog,
                                      icon: const Icon(Icons.cancel),
                                      label: const Text('取消签到'),
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: Colors.red,
                                        foregroundColor: Colors.white,
                                      ),
                                    )
                                  : ElevatedButton.icon(
                                      onPressed: _showCheckInForm,
                                      icon: const Icon(Icons.check),
                                      label: const Text('立即签到'),
                                    ),
                            ],
                          ),
                        ),
                      ),
                      
                      // 签到统计卡片
                      _buildStatsCard(),
                      
                      // 签到记录列表
                      Padding(
                        padding: const EdgeInsets.all(16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '签到记录',
                              style: Theme.of(context).textTheme.titleLarge,
                            ),
                            Text('共 ${_checkIns.length} 条记录'),
                          ],
                        ),
                      ),
                      ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: _checkIns.length,
                        itemBuilder: (context, index) {
                          final checkIn = _checkIns[index];
                          final date = DateTime.fromMillisecondsSinceEpoch(checkIn.date);
                          final dateStr = DateFormat('yyyy-MM-dd').format(date);
                          final createdAt = DateTime.fromMillisecondsSinceEpoch(checkIn.createdAt);
                          
                          return Card(
                            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                            child: ListTile(
                              leading: const Icon(Icons.calendar_today),
                              title: Text(dateStr),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('签到时间: ${DateFormat('HH:mm:ss').format(createdAt)}'),
                                  if (checkIn.studyTime > 0 || checkIn.wordsLearned > 0 || checkIn.questionsAnswered > 0)
                                    Text(
                                      '学习: ${checkIn.studyTime}分钟 | 单词: ${checkIn.wordsLearned} | 答题: ${checkIn.questionsAnswered}',
                                    ),
                                  if (checkIn.note.isNotEmpty) Text('备注: ${checkIn.note}'),
                                ],
                              ),
                              isThreeLine: true,
                              trailing: IconButton(
                                icon: const Icon(Icons.info_outline),
                                onPressed: () => _showCheckInDetails(checkIn),
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
                
                // 数据页面
                SingleChildScrollView(
                  child: Column(
                    children: [
                      _buildStatsCard(),
                      _buildCheckInChart(),
                      // 数据表格
                      Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('签到数据表', style: Theme.of(context).textTheme.titleLarge),
                            const SizedBox(height: 16),
                            SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              child: DataTable(
                                columns: const [
                                  DataColumn(label: Text('日期')),
                                  DataColumn(label: Text('学习时长')),
                                  DataColumn(label: Text('单词数')),
                                  DataColumn(label: Text('答题数')),
                                ],
                                rows: _checkIns.map((record) {
                                  final date = DateTime.fromMillisecondsSinceEpoch(record.date);
                                  final dateStr = DateFormat('yyyy-MM-dd').format(date);
                                  return DataRow(cells: [
                                    DataCell(Text(dateStr)),
                                    DataCell(Text('${record.studyTime}分钟')),
                                    DataCell(Text('${record.wordsLearned}')),
                                    DataCell(Text('${record.questionsAnswered}')),
                                  ]);
                                }).toList(),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 目标页面
                Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('签到目标', style: Theme.of(context).textTheme.titleLarge),
                          ElevatedButton.icon(
                            onPressed: _showAddGoalForm,
                            icon: const Icon(Icons.add),
                            label: const Text('添加目标'),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      child: _goals.isEmpty
                          ? const Center(child: Text('暂无签到目标，点击右上角添加'))
                          : ListView.builder(
                              itemCount: _goals.length,
                              itemBuilder: (context, index) {
                                final goal = _goals[index];
                                return Card(
                                  margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                                  child: ListTile(
                                    title: Text(goal.title),
                                    subtitle: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        if (goal.description.isNotEmpty) Text(goal.description),
                                        Text('目标: ${goal.targetValue} ${goal.unit}'),
                                      ],
                                    ),
                                    trailing: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Switch(
                                          value: goal.isActive,
                                          onChanged: (value) => goal.id != null
                                              ? _toggleGoalActive(goal.id!, value)
                                              : null,
                                        ),
                                        IconButton(
                                          icon: const Icon(Icons.delete),
                                          onPressed: () => goal.id != null
                                              ? _showDeleteGoalConfirmDialog(goal.id!)
                                              : null,
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                    ),
                  ],
                ),
              ],
            ),
    );
  }
  
  // 显示签到详情
  void _showCheckInDetails(CheckInRecord record) {
    final date = DateTime.fromMillisecondsSinceEpoch(record.date);
    final dateStr = DateFormat('yyyy-MM-dd').format(date);
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('$dateStr 签到详情'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('学习时长: ${record.studyTime} 分钟'),
              Text('学习单词: ${record.wordsLearned} 个'),
              Text('答题数量: ${record.questionsAnswered} 题'),
              if (record.note.isNotEmpty) ...[const SizedBox(height: 8), Text('备注: ${record.note}')],
              if (record.goalProgress.isNotEmpty) ...[const SizedBox(height: 16), const Text('目标进度:')],
              if (record.goalProgress.isNotEmpty)
                ...record.goalProgress.entries.map((entry) {
                  final goalId = entry.key;
                  final progress = entry.value;
                  // 查找目标，如果找不到则跳过这个目标进度
                  final goalIndex = _goals.indexWhere((g) => g.id == goalId);
                  if (goalIndex == -1) return const SizedBox.shrink(); // 如果找不到目标，不显示
                  
                  final goal = _goals[goalIndex];
                  return Padding(
                    padding: const EdgeInsets.only(top: 4),
                    child: Text('${goal.title}: $progress ${goal.unit}'),
                  );
                }).where((widget) => widget != const SizedBox.shrink()).toList(),
              if (record.goalProgress.isEmpty) ...[const SizedBox(height: 16), const Text('暂无目标进度')],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }
  
  // 显示删除目标确认对话框
  void _showDeleteGoalConfirmDialog(int id) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除目标'),
        content: const Text('确定要删除这个签到目标吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _deleteGoal(id);
            },
            child: const Text('删除'),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
          ),
        ],
      ),
    );
  }
}